<script setup lang="ts">
import { barcodeScanWxPayApi, getBarcodeAllPriceAPI } from '@/api/code'
import type { ActBarcodeModel } from '@/types/code'
import { ref } from 'vue'
import { busListStore } from '@/stores'
import { useMemberStore } from '@/stores'
import type { WxChatPayDto } from '@/types/global'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

const form = ref<ActBarcodeModel>({
  busId: '',
  acsType: '1',
  codeNo: '',
  openId: '',
})

const amount = ref('0')
const scanList = ref<Array<string>>([])
const busStore = busListStore()
const memberStore = useMemberStore()

const onTpyeChange: UniHelper.RadioGroupOnChange = (ev) => {
  form.value.acsType = ev.detail.value
  resetForm()
}

// 扫码获取信息
const openScanner = async () => {
  // 调用uni.scanCode()函数进行扫一扫操作
  uni.scanCode({
    success(res: UniApp.ScanCodeSuccessRes) {
      let code = res.result.split(',')[0]
      if ((code.includes('ALCM') && form.value.acsType == '2') || (code.includes('BA') && form.value.acsType == '1')) {
        if (scanList.value.some((item) => item.includes(code))) {
          uni.showToast({ icon: 'none', title: '该码已经扫描过，请更换乐促码扫描' })
        } else {
          scanList.value.push(code)
        }

        getBarcodeAllPrice()
      } else {
        uni.showToast({ icon: 'none', title: '整版录入请扫整版码！' })
      }
    },
  })
}

// 计算价格
const getBarcodeAllPrice = async () => {
  let obj = {
    acsType: form.value.acsType!,
    codeNo: scanList.value.join(','),
  }
  const res = await getBarcodeAllPriceAPI(obj)
  uni.showToast({ icon: 'none', title: res.msg })
  amount.value = res.data
}

// 整板码输入检索
const allSearch = () => {
  if (form.value.codeNo) {
    scanList.value[0] = form.value.codeNo
    getBarcodeAllPrice()
  } else {
    uni.showToast({ icon: 'none', title: '请输入或者扫描整板码' })
  }
}

// 构建支付参数
const paymentParams = ref<WxChatPayDto>({})

// 付款
const onSubmit = async () => {
  if (scanList.value.length > 0) {
    // 组装数据
    form.value.codeNo = scanList.value.join(',')
    if (busStore.busList.length > 0) {
      form.value.busId = busStore.busList[0].id
      form.value.busName = busStore.busList[0].name
    }
    if (memberStore.profile) {
      form.value.openId = memberStore.profile.wxOpenid
    }
    const res = await barcodeScanWxPayApi(form.value)
    paymentParams.value = res.data
    // 调用微信支付
    uni.requestPayment<any>({
      provider: 'wxpay',
      timeStamp: paymentParams.value.timeStamp,
      nonceStr: paymentParams.value.nonceStr,
      package: paymentParams.value.prepayId,
      signType: paymentParams.value.signType,
      paySign: paymentParams.value.paySign,
      success(res: any) {
        resetForm()
        // 支付成功回调
        uni.showToast({ icon: 'success', title: '支付成功' })
      },
      fail(err: any) {
        // 支付失败回调
        uni.showToast({ icon: 'fail', title: '支付失败' })
      },
    })
  } else {
    uni.showToast({ icon: 'none', title: '请扫码录入乐促码在，进行激活操作' })
  }
}

const resetForm = () => {
  form.value.codeNo = ''
  scanList.value = []
  amount.value = '0'
}
</script>

<template>
  <!-- 表单 -->
  <view class="form">
    <!-- 表单内容 -->
    <view class="form-content">
      <view class="form-item">
        <text class="label">录入方式</text>
        <radio-group @change="onTpyeChange">
          <label class="radio">
            <radio value="1" color="#27ba9b" :checked="form.acsType == '1'" />
            整版录入
          </label>
          <label class="radio">
            <radio value="2" color="#27ba9b" :checked="form.acsType == '2'" />
            单个录入
          </label>
        </radio-group>
      </view>
      <view class="form-item" v-show="form.acsType == '1'">
        <text class="label">录入编码</text>
        <input class="input" type="text" placeholder="录入12位整板码编码" v-model="form.codeNo" maxlength="16" />
        <button class="all_btn" @tap="allSearch">检索</button>
      </view>
      <view class="scan_list">
        <template v-if="scanList.length > 0">
          <view class="scan_item" v-for="item in scanList" :key="item">
            <uni-tag :inverted="true" :text="item" type="primary" />
          </view>
        </template>
        <view class="noscanitem" v-show="scanList.length==0">请扫码录入</view>
        <button class="form-button" @tap="openScanner">扫码录入</button>
      </view>
    </view>
  </view>
  <!-- 用户操作 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="left_text">
      付费金额：<text>{{ amount }}</text> 元
    </view>
    <view class="buttons">
      <button class="buynow" :disabled="amount <= '0'" @tap="onSubmit">立即付款</button>
    </view>
  </view>
</template>

<style lang="scss">
.title {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding-left: 15px;
  height: 40px;
  background-color: #ddd;
  font-weight: normal;
  color: #666;
  font-size: 14px;
}
.all_btn {
  background-color: #27ba9b;
  color: #fff;
  font-size: 12px;
  height: 23px;
  line-height: 23px;
}
// 表单
.form {
  background-color: #f4f4f4;
  padding-top: 10rpx;
  padding-bottom: 40rpx;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
    .code {
      color: #27ba9b;
      font-size: 28rpx;
    }
    .send {
      color: #999;
    }
  }
  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
  .scan_list {
    height: auto;
    display: flex;
    flex-wrap: wrap;
    padding: 20rpx 0;
    .scan_item {
      margin: 10rpx;
      color: #27ba9b;
    }
    .noscanitem {
      text-align: center;
      padding: 10px;
      font-size: 14px;
      color: #999;
      width: 100%;
    }
  }
  .form-button {
    width: 100%;
  }
}
/* 底部工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  .left_text {
    font-size: 26rpx;
    color: #999;
    text {
      font-size: 40rpx;
      color: #cf4444;
    }
  }
  .buttons {
    display: flex;
    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }
    .addcart {
      background-color: #ffa868;
    }
    .buynow,
    .payment {
      background-color: #27ba9b;
      margin-left: 20rpx;
      color: #fff;
      font-size: 14px;
    }
  }
}
</style>
